package com.codeyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.codeyang.domain.UserAddr;
import com.codeyang.service.UserAddrService;
import com.codeyang.util.LoadUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 描述:
 *
 * @author CodeYang_Site
 * @version 2021/5/28 15:06
 */
@Api
@RestController
@RequestMapping("p/address")
public class UserAddrController {

    @Autowired
    private UserAddrService userAddrService;


    @GetMapping("list")
    @ApiOperation("加载用户收货地址")
    public ResponseEntity<List<UserAddr>> loadUserAddress() {
        String userId = LoadUserInfoUtil.getUserId();
        List<UserAddr> userAddrList = userAddrService.findUserAddr(userId);
        return ResponseEntity.ok(userAddrList);
    }

    @PostMapping("addAddr")
    @ApiOperation("新增用户的收货地址")
    public ResponseEntity<Void> addUserAddr(@RequestBody @Validated UserAddr userAddr) {
        String userId = LoadUserInfoUtil.getUserId();
        userAddr.setUserId(userId);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }


    @PutMapping("defaultAddr/{id}")
    @ApiOperation("修改用户的默认收货地址")
    public ResponseEntity<Void> changeUserDefaultAddr(@PathVariable("id") Long id) {
        String userId = LoadUserInfoUtil.getUserId();
        userAddrService.changeUserAddr(userId, id);
        return ResponseEntity.ok().build();
    }


    /**
     * 远程调用 查询用户默认收货地址
     *
     * @param userId
     * @return
     */
    @GetMapping("getUserDefaultAddr")
    public UserAddr getUserDefaultAddr(@RequestParam String userId) {
        return userAddrService.getOne(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId, userId)
                .eq(UserAddr::getCommonAddr, 1)
        );
    }


}
